import React, {useState, useEffect} from 'react'
import { createPortal } from 'react-dom'
import styles from './dropDown.module.scss'
import {DatePicker, Button, Dropdown, Menu, Space} from 'antd'

const menu = (
  <Menu
    items={[
      {
        key: '1',
        label: (
          <a target="_blank" rel="noopener noreferrer" href="https://www.antgroup.com">
            1st menu item
          </a>
        ),
      },
      {
        key: '2',
        label: (
          <a target="_blank" rel="noopener noreferrer" href="https://www.aliyun.com">
            2nd menu item
          </a>
        ),
      },
      {
        key: '3',
        label: (
          <a target="_blank" rel="noopener noreferrer" href="https://www.luohanacademy.com">
            3rd menu item
          </a>
        ),
      },
    ]}
  />
);
interface DropWrapProps {
  open: boolean;
  active: boolean;
  className: string;
  childrens: React.ReactNode | string;
  site: {
    top: string;
    left: string;
  };
  onTransitionEnd: () => void;
  leave: () => void;
}
interface DropProps {
  children: React.ReactNode;
  title?: React.ReactNode | string;
  className: string;
  // site: {
  //   top: number;
  //   left: number;
  // }
}



const DropWrap = (props: DropWrapProps) => {
  if(!props.open && !props.active) return null
  return createPortal(
    <div className={props.className}
      style={{
        ...props.site
      }}
      // 在动画转换结束时执行
      onTransitionEnd={props.onTransitionEnd}
      // onMouseLeave={props.leave}
    > 
      {props.childrens}
    </div>,
    document?.getElementsByTagName('body')[0]
  )
}


/*
  展开动效的顺序：enter -> enter-active -> enter-done
  关闭动效的顺序：exit -> exit-active -> exit-done
  动效过程在 enter-active 和 exit-active 的过程中
*/
const Drop = (props: DropProps) => {
  // 是否存在 window document等对象
  const [showDom, setShowDom] = useState(false)
  // 动效 class
  const [aniClassName, setAniClassName] = useState("")

  // 只控制是执行展开动效还是关闭动效
  const [open, setOpen] = useState(false)
  // 控制是关闭动效是否已执行关闭
  const [active, setActive] = useState(false)
  // 展示的位置
  const [site, setSite] = useState({
    top: "-999px", // props.site.top >= 0 ? props.site.top+'px' :
    left: "-999px", // props.site.left >= 0 ? props.site.left+'px' : 
  })


  // transition 执行完毕的监听函数
  const onTransitionEnd = () => {
    // 当open为true时，则结束状态为 enter-done
    // 当open为false时，则结束状态为 exit-done
    setAniClassName(open ? 'enter-done' : 'exit-done')
    if(!open) {
      console.log('执行时间！！！！')
      setActive(false)
    }
  }



  useEffect(() => {
    if(open) {
      setActive(true)
      setAniClassName('enter')
      // setTimeout用来切换class，让transition动起来
      setTimeout(() => {
        setAniClassName('enter-active')
      })
    } else {
      setAniClassName('exit')
      setTimeout(() => {
        setAniClassName('exit-active')
      })
    }
  }, [open])

  useEffect(() => {
    setShowDom(true)
    // fetch("https://818ps.com/apiv3/get-count-for-template-type?nonce=Lh0By5PprfUb&timestamp=1659945363&token=oar6mrsrs6svmvih38mbdsnki1&template_type=1&class_id=0&sign=1214021b66f5377dfa72f0864f7c95c5")
    //   .then(data => data.json())
    //   .then(res => {
    //     console.log(res,' husajfis')
    //   })

    // fetch("https://818ps.com/apiv3/search?nonce=5ZRtOQuFHkAe&timestamp=1659945945&token=oar6mrsrs6svmvih38mbdsnki1&page=1&template_type=1&class_id=0_0_0_0&sign=9017c6624956608359066319333d9075")
    //   .then(data => data.json())
    //   .then(res => {
    //     console.log(res,' husajfis 2222')
    //   })
  }, [])

  return (
    <div
      className={props.className}
      // {...props}
      onMouseEnter={(e) => {
        e.stopPropagation();
        e.nativeEvent.stopPropagation();
        e.nativeEvent.stopImmediatePropagation();
        setShowDom(true)
        setOpen(true)
        setActive(true)
        setSite({
          top: e.currentTarget.offsetTop + e.currentTarget.offsetHeight + 'px',
          left: e.currentTarget.offsetLeft + 'px'
        })
      }}
      onMouseLeave={(e) => {
        e.stopPropagation();
        e.nativeEvent.stopPropagation();
        e.nativeEvent.stopImmediatePropagation();
        console.log('leave!!!!')
        setOpen(false)
        // setSite({
        //   top: "-999px",
        //   left: "-999px"
        // })
      }}
    >
      { props.title }
      {/* { DropWrap } */}
      <DropWrap 
        className={[
          styles.portal_drop,
          styles[aniClassName],
        ].join(' ')}
        open={open}
        active={active}
        site={site}
        onTransitionEnd={onTransitionEnd}
        leave={() => {
          setOpen(false)
        }}
        childrens={props.children}
      />
    </div>
  )
}



// 
export default function DropDown() {

  return (
    <div>
      DropDown
      <Dropdown overlay={menu} placement="bottom">
        <Button>DropDown</Button>
      </Dropdown>

      <Drop
        className={styles.hover_drop_down}
        title={(
          <div>hover drop down 123</div>
        )}
      >
        {/* {menu} */}
        <div className={styles.test}>
          这是一哈死的风景就啊快结束的发夹哦多开房间阿克苏地方和湿地恢复
        </div>
      </Drop>

      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
      </ul>
    </div>
  )
}
